import React, { useState, useEffect } from 'react';
import { Dlg, is_empty, Info, obj_str, show_side, ck_empty, KFind, cline, uDb, KDlg, obj_int, KInput, ck_int, loc, useKForm } from 'sui';
import { get_tp } from './cmd';

const DlgVal = (props) => {
    const [tech, setTech] = useState();
    const form = useKForm();

    useEffect(() => {
        if (!props.open) {
            return;
        }

        const cmd = { line: cline() }

        uDb(null, "tech/list", cmd, r => setTech(r), e => setTech(null));
    }, [props.open]);

    const ck = {
        tech : v => {
            const e = ck_empty(v);
            if (e) {
                return e;
            }

            const cur_tech = tech.find(d => d.sn === v);
            if (!cur_tech) {
                return loc("l_758");
            }

            const ball = obj_str(cur_tech, "ball");

            const old = props.data;

            const old_mt = get_tp(props.mod);
            const old_ball = obj_str(old, "ball");

            if (ball !== old_ball) {
                return loc("l_760");
            }

            if (old_mt === "G" || old_mt === "T") {
                const mt = obj_str(cur_tech, "mt");
                if (mt !== old_mt) {
                    return loc("l_759");
                }
            } else {
                const old_tech = obj_str(old, "tech");
                const tech_sn = obj_str(cur_tech, "sn");
                if (tech_sn.indexOf(old_tech) < 0) {
                    return loc("l_759");
                }
            }

            return null;
        },
        side : v => ck_empty(v),
        num : v => {
            const e = ck_int(v);
            if (e) {
                return e;
            }

            const n = parseInt(v, 10);
            const dnum = obj_int(props.data, "dnum");
            if (n > dnum) {
                return loc("l_707");
            }

            return null;
        }
    };

    const side = [
        {sn: "hand", name: show_side("hand")},
        {sn: "auto", name: show_side("auto")},
    ];

    return (
        <KDlg {...props} title={loc("l_741")} ck={ck} form={form}>
            <KFind label={loc("l_177")} form={form} name="tech" list={tech}/>
            <KFind label={loc("l_757")} form={form} name="side" list={side}/>
            <KInput label={loc("l_127")} form={form} name="num"/>
        </KDlg>
    );
};

const DlgNum = ({ open, setOpen, hcmd, data, fin, col, mod }) => {
    const [tech, setTech] = useState();
    const form = useKForm();

    useEffect(() => {
        if (!open) {
            return;
        }

        if (mod === "forge" && fin === "out") {
            let cur_tech = obj_str(data, "tech");
            cur_tech = cur_tech.split("-");

            const ball = cur_tech[cur_tech.length - 1];
            cur_tech = cur_tech[0];

            let cur_std = obj_str(data, "std");
            cur_std = cur_std.split("-");
            cur_std = cur_std[cur_std.length - 1];

            const cmd = { line: cline() }
            const ret = [];

            uDb(null, "tech/list", cmd,
                r => {
                    r.forEach(d => {
                        if (d.ball !== ball) {
                            return;
                        }

                        if (d.sn.indexOf(cur_tech) < 0) {
                            return;
                        }

                        const t = `${obj_str(d, "sn")}-${cur_std}`;
                        d["tech"] = d["sn"];
                        d["sn"] = t;
                        d["name"] = t;

                        ret.push(d);
                    });

                    setTech(ret);
                },
                e => setTech(null));
        }
    }, [open, fin, mod, data]);

    const is_tech = () => mod === "forge" && fin === "out";

    const hok = () => {
        const ck = {
            dnum: v => {
                const e = ck_int(v);
                if (e) {
                    return e;
                }

                if (fin === "out") {
                    const bnum = obj_int(data, "bnum");
                    if (v > bnum) {
                        return loc("l_731");
                    }
                }

                return null;
            }
        };

        if (is_tech()) {
            ck["tech"] = v => ck_empty(v);
        }

        if (form.isErr(ck)) {
            return;
        }

        const cmd = {
            dnum: obj_int(form.value, "dnum"),
        };

        if (is_tech()) {
            const t = form.get("tech");
            const f = tech.find(d => d.sn === t);

            cmd["tech"] = f.tech;
            cmd["std"] = t;
        }

        form.clear();
        setOpen(false);
        hcmd(cmd);
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const v = ["sn", "tech", "std"];

        if (fin === "out") {
            v.push("bnum");
        } else {
            v.push("dnum");
        }

        const set = new Set();

        v.forEach(d => set.add(d));

        const tmp = [];

        col.forEach(d => {
            if (set.has(d.sn)) {
                tmp.push(d);
            }
        });

        return tmp;
    };

    const getTitle = () => {
        if (fin === "out") {
            return loc("l_139");
        }

        if (fin === "in") {
            return loc("l_147");
        }

        return loc("l_741");
    };

    const getHl = () => {
        if (fin === "out") {
            return ["bnum"];
        } else {
            return ["dnum"];
        }
    };

    const getTech = () => {
        if (is_tech()) {
            return <KFind label={loc("l_363")} form={form} name="tech" list={tech}/>;
        }

        return null;
    };

    return (
        <Dlg open={open} hcancel={() => setOpen(false)} hcmd={hok} title={getTitle()}>
            <Info data={data} col={getCol()} hl={getHl()}/>
            <KInput label={loc("l_127")} form={form} name="dnum"/>
            {getTech()}
        </Dlg>
    );
};

export {DlgNum, DlgVal};
